import { drawType } from './draw-type';
import { defaultTextStyle } from './default-style';

export const initPos = {
  totalScale: 1,
  totalScaleMax: 16,
  totalScaleMin: 0.25,
  scale: 1,
  lastScale: 1,
  cx: 0,
  cy: 0,
  lastCx: 0,
  lastCy: 0,
  drawData: null,
  mouseDown: false,
  moveFromX: 0,
  moveFromY: 0,
  deltaX: 0,
  deltaY: 0,
}
export const round = function (number, count) {
  if (!count) {
    count = 0;
  }
  const regExp = new RegExp(`(.*\\..{${count}}).*$`, 'g');
  let value = String(number).replace(regExp, '$1');
  return parseFloat(value);
};
function checkLimitMove(drawList,defaultDeltaParam){
  drawList.forEach(drawList => {
    drawList.children.forEach(drawParam => {
      if(drawParam.type === drawType.LIMIT){
        defaultDeltaParam = drawParam.checkMove(defaultDeltaParam.deltaX,defaultDeltaParam.deltaY);
      }
    });
  });
  return defaultDeltaParam;
}
export const move = function (drawList, param) {
  param = checkLimitMove(drawList,param);
  if(param.deltaY === 0 && param.deltaY === 0){
    return false;
  }
  drawList.forEach((draw) => {
    draw.children.forEach((d) => {
      if (d.move && d.movable !== false) {
        d.move(param.deltaX, param.deltaY);
      }
    });
  });
  return true;
};
export const zoom = function (drawList, param) {
  drawList.forEach((draw) => {
    draw.children.forEach((d) => {
      if (d.zoom && d.zoomAble !== false) {
        d.zoom(param.cx, param.cy, param.scale, param.totalScale);
      }
    });
  });
};
/**
 * 初始整理缩放设置
 * @param drawData 画图数据，对象或数组
 * @param initScale 缩放倍数
 * @param scaleBorder 线宽是否缩放
 * @param scaleText 文字是否缩放
 */
export const drawDataInitScale = function (drawData,initScale,scaleBorder,scaleText){
  if(!initScale){
    let dpr = window.devicePixelRatio || 1;
    initScale = 1 / dpr;
  }
  if(!drawData){
    return;
  }
  if(drawData.constructor === Array){
    drawData.forEach((draw) => {
      drawDataInitScale(draw,initScale,scaleBorder,scaleText)
    });
  }
  settingInitScale(drawData.children,initScale,scaleBorder,scaleText);

}

function settingInitScale(children,initScale,scaleBorder,scaleText){
  if(children){
    children.forEach((child) => {
      if(!child){
        return;
      }
      child.setScale(initScale);
      if(scaleBorder !== undefined){
        child.isBorderScale = scaleBorder;
      }
      if(scaleText !== undefined){
        child.isTextScale = scaleText;
      }
      settingInitScale(child.children,initScale,scaleBorder,scaleText);
    });
  }
}

export const findObjectValue = function (tag, values) {
  if (typeof tag === 'number') {
    return tag;
  }
  if (!tag || !values) {
    return {};
  }

  let startIndex = tag.indexOf('{');
  let endIndex = tag.indexOf('}');
  let value;
  if (startIndex === -1 || endIndex === -1 || endIndex - 1 <= startIndex) {
    value = values[tag];
  } else {
    let name = tag.substring(startIndex + 1, endIndex);
    value = values[name];
  }
  return value ? value : {};
};

export const findText = function (text, values) {
  let startIndex = text.indexOf('{');
  let endIndex = text.indexOf('}');
  if (startIndex === -1 || endIndex === -1) {
    return text;
  }
  if (endIndex - 1 > startIndex) {
    let name = text.substring(startIndex + 1, endIndex);
    let value = values[name];
    let startIndex2 = text.indexOf('[');
    let endIndex2 = text.indexOf(']');
    if (typeof value !== 'undefined' && startIndex2 === endIndex + 1 && endIndex2 - 1 > startIndex2) {
      let name2 = text.substring(startIndex2 + 1, endIndex2);
      let value2 = value[name2];
      if (typeof value2 === undefined) {
        value2 = '';
      }
      return text.replace('{' + name + '}[' + name2 + ']', value2);
    } else {
      return text.replace('{' + name + '}', '');
    }
  } else {
    return text;
  }
};

export const getFontAttr = function (drawParam,values) {
  let fontAttr;
  let start = drawParam.start;
  let end = drawParam.end;
  if (!start) {
    start = [0, 0];
  }
  if (!end) {
    end = start;
  }
  if (drawParam.type === drawType.TEXT) {
    fontAttr = Object.assign({}, drawParam.style, defaultTextStyle, drawParam.fontStyle);
  } else {
    fontAttr = Object.assign({}, defaultTextStyle, drawParam.fontStyle);
  }
  if(drawParam.checkFontStyle){
    Object.assign(fontAttr,drawParam.checkFontStyle({drawParam: drawParam,values: values}))
  }
  if (fontAttr.textAlign) {
    let textAlign = fontAttr.textAlign;
    if (textAlign === 'left' || textAlign === 'start' || textAlign === 'none' || textAlign === '') {
      fontAttr.textAnchor = 'start';
    } else if (textAlign === 'right' || textAlign === 'end') {
      fontAttr.textAnchor = 'end';
    } else {
      fontAttr.textAnchor = 'middle';
    }
  }
  let textAnchor = fontAttr.textAnchor;
  if (textAnchor === 'left' || textAnchor === 'start') {
    fontAttr.textAnchor = 'start';
    fontAttr.x = start[0] + 2;
  } else if (textAnchor === 'right' || textAnchor === 'end') {
    fontAttr.textAnchor = 'end';
    fontAttr.x = end[0] - 4;
  } else if (textAnchor === 'middle' || textAnchor === 'center') {
    fontAttr.textAnchor = 'middle';
    fontAttr.x = (start[0] + end[0]) / 2;
  } else {
    fontAttr.x = start[0];
  }
  //    // hanging 上对齐，middle居中对其， ideographic 底下对齐
  if (fontAttr.textBaseline) {
    let textBaseline = fontAttr.textBaseline;
    if (textBaseline === 'top' || textBaseline === 'hanging') {
      fontAttr.dominantBaseline = 'hanging';
    } else if (textBaseline === 'bottom' || textBaseline === 'ideographic') {
      fontAttr.dominantBaseline = 'ideographic';
    } else {
      fontAttr.dominantBaseline = 'middle';
    }
  }
  let dominantBaseline = fontAttr.dominantBaseline;
  if (dominantBaseline === 'top' || dominantBaseline === 'hanging') {
    fontAttr.y = start[1];
  } else if (dominantBaseline === 'bottom' || dominantBaseline === 'ideographic') {
    fontAttr.y = end[1];
  } else {
    fontAttr.y = (start[1] + end[1]) / 2 + 1;
  }
  delete fontAttr.textAlign;
  delete fontAttr.textBaseline;
  return fontAttr;
};

export const checkInTriangle = function (x0, y0, x1, y1, x2, y2, x3, y3) {
  let divisor = (y2 - y3) * (x1 - x3) + (x3 - x2) * (y1 - y3);
  let a = ((y2 - y3) * (x0 - x3) + (x3 - x2) * (y0 - y3)) / divisor;
  let b = ((y3 - y1) * (x0 - x3) + (x1 - x3) * (y0 - y3)) / divisor;
  let c = 1 - a - b;
  return a >= 0 && a <= 1 && b >= 0 && b <= 1 && c >= 0 && c <= 1;
};
Date.prototype.format = function(fmt) {
  let o = {
    "M+" : this.getMonth()+1,                 //月份
    "d+" : this.getDate(),                    //日
    "H+" : this.getHours(),                   //小时
    "m+" : this.getMinutes(),                 //分
    "s+" : this.getSeconds(),                 //秒
    "q+" : Math.floor((this.getMonth()+3)/3), //季度
    "S"  : this.getMilliseconds()             //毫秒
  };
  if(/(y+)/.test(fmt)) {
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
  }
  for(let k in o) {
    if(new RegExp("("+ k +")").test(fmt)){
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length===1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
    }
  }
  return fmt;
}